package dbi.org.api;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import dbi.org.exception.DbConnectionCloseException;
import dbi.org.exception.DbConnectionAlreadyExistsException;
import dbi.org.exception.DbConnectionException;

public class ConnectionManager {
	private boolean hasConnection = false;
	public Connection conn = null;
	
	private static ConnectionManager cm = new ConnectionManager();
	private static String userName = "root";
	private static String password = "hamham";
	private static String url = "jdbc:mysql://localhost:3306/menm";
	
	public ConnectionManager() {}
	
	public static ConnectionManager getInstance( ) {
		return cm;
	}
	
	public boolean hasConnection() {
		return hasConnection;
	}
	
	public void openConnection() throws DbConnectionException, DbConnectionAlreadyExistsException{
		if(hasConnection == false){
	        try{
	            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
	            conn = DriverManager.getConnection (url, userName, password);
	            System.out.println ("Database connection established");
	            hasConnection = true;
	        }
	        catch (Exception e){
	            throw new DbConnectionException();
	        }
		} else {
			throw new DbConnectionAlreadyExistsException();
		}
	}
	
	public Connection getConnection() {
		return conn;
	}
	
	public void closeConnection() throws DbConnectionCloseException{
		try {
			conn.close();
			hasConnection = false;
			System.out.println("Database connection closed");
			
		} catch (SQLException e) {
			throw new DbConnectionCloseException();
		}
	}

}
